package com.stroke.core;

import com.stroke.core.helpers.RenderHelper;
import com.stroke.core.helpers.UpdateHelper;
import com.stroke.entity.Entity;
import com.stroke.graphics.ScreenManager;

import java.awt.*;
import java.util.ArrayList;
import java.util.List;

/**
 * Author: Igor Bubelov
 * Date: 3/5/11 7:54 PM
 */
public class EntityManager {
    private static EntityManager instance;

    private ScreenManager screenManager;

    private List<Entity> entities = new ArrayList<Entity>();
    private List<Entity> entitiesToAdd = new ArrayList<Entity>();
    private List<Entity> entitiesToRemove = new ArrayList<Entity>();

    private EntityManager() { }

    public static EntityManager getInstance() {
        return instance = instance == null ? new EntityManager() : instance;
    }

    public void setScreenManager(ScreenManager manager) {
        this.screenManager = manager;
    }

    public synchronized void update() {
        entities.addAll(entitiesToAdd);
        entitiesToAdd.clear();

        entities.removeAll(entitiesToRemove);
        entitiesToRemove.clear();

        UpdateHelper.processInput(entities, screenManager.getInputHandler());

        for (Entity entity : entities) {
            entity.step();
        }

        screenManager.getScreen().requestFocus();
    }

    public synchronized void render() {
        Graphics2D g = RenderHelper.prepare(screenManager);

        Rectangle area = screenManager.getViewArea();

        RenderHelper.renderEntities(entities, g, area);

        screenManager.show();
    }

    public void addEntity(Entity entity) {
        entitiesToAdd.add(entity);
    }

    public void removeEntity(Entity entity) {
        entitiesToRemove.add(entity);
    }
}